<template>
  <div class="inputContainer">
    <span @click="doFocus" ref="text" class="placeholder">{{ placeholder }}</span>
    <div>
      <el-input v-if="type==='text'"
                ref="input"
                type="text"
                v-model="inputValue"
                @keydown.enter.native="keydownEnter"
                @focus="inputFocus"
                @blur="inputBlur"
                @input="changeInput"/>
      <el-input v-else
                ref="input"
                type="password"
                v-model="inputValue"
                @keydown.enter.native="keydownEnter"
                @focus="inputFocus"
                @blur="inputBlur"
                @input="changeInput"/>
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "FFAInput",
  data() {
    return {
      inputValue: ''
    }
  },
  props: {
    // 输入框传入的值
    value: {
      type: [String, Number],
      default: ''
    },
    // span中的文字
    placeholder: {
      type: String,
      default: ''
    },
    // 按回车事件
    keydownEnter: {
      type: Function,
      default: () => {
      }
    },
    // 输入框type
    type: {
      type: [String],
      default: 'text'
    }
  },
  methods: {
    changeInput($event) {
      // 向上派发myInput事件，这样model监听myInput才有意义：当输入字符时触发input事件，
      // 进而派发触发自定义的myInput事件，然后model监听myInput，就实现了数据绑定
      this.$emit('input', $event)
    },
    // 输入框聚焦，placeholder上升
    inputFocus() {
      this.$refs.text.style.top = '0'
    },
    // 输入框失焦，如果输入框中无内容，则placeholder下降
    inputBlur() {
      if (this.inputValue === '' || this.inputValue == null) {
        this.$refs.text.style.top = '25px'
      }
    },
    // 点击placeholder使输入框聚焦
    doFocus() {
      this.$refs.input.focus()
    }
  }
}
</script>

<style scoped>
.inputContainer {
  margin: 50px auto 0;
  width: 300px;
}

.placeholder {
  color: var(--lightText);
  font-weight: lighter;
  position: relative;
  top: 25px;
  z-index: 1;
  cursor: text;
  transition: 0.5s;
}
</style>